package com.module.my.set.view

import android.hardware.biometrics.BiometricPrompt
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import com.module.biometric.ACacheUtils
import com.module.biometric.BiometricPromptManager
import com.module.biometric.BiometricPromptManager.OnBiometricIdentifyCallback
import com.module.app.base.BaseFragment
import com.module.app.bean.ConfigBean
import com.module.app.pop.CommonPop
import com.module.app.bean.IType
import com.module.base.cache.CacheSDK
import com.module.app.utils.EncodeNameUtils
import com.module.base.utils.ToastUtils
import com.module.base.BuildConfig
import com.module.frame.app.AppManager
import com.module.frame.ext.observe
import com.module.my.R
import com.module.my.databinding.MyFragSetPasswordBinding
import com.module.my.set.model.SetPasswordModel


/**
 * Author: yanxuwen
 * Date: 2023/3/17
 * Desc: 密码相关
 */
class SetPasswordFragment : BaseFragment<SetPasswordModel, MyFragSetPasswordBinding>() {

    private var fingerprintTips = false
    private val mManager: BiometricPromptManager by lazy {
        BiometricPromptManager.from(AppManager.getInstance().currentActivity(), true, true);
    }

    override fun bingViewModel() {
        mDatabind.vm = mViewModel
        mViewModel.context = context
    }

    override fun onLazyLoad() {
    }

    override fun onResume() {
        super.onResume()
        checkFingerprint()
    }

    override fun initListener() {
        super.initListener()
        observe(mViewModel.commonPasswordFlow) {
            setCommonPassword()
        }
        mDatabind.sbClosePassword.setOnCheckedChangeListener { _, isChecked ->
            CacheSDK.put(IType.ICache.CLOSE_PASSWORD, !isChecked)
            mDatabind.vFingerprintMask.visibility = if (isChecked) View.GONE else View.VISIBLE
            mDatabind.layoutFingerprint.alpha = if (isChecked) 1f else 0.3f
        }
        mDatabind.sbFingerprint.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                initBiometric()
            } else {
                CacheSDK.put(IType.ICache.FINGERPRINT, false)
            }
        }
    }

    override fun initData() {
        super.initData()
        //关闭锁屏密码
        val closePassword = CacheSDK.get(
            IType.ICache.CLOSE_PASSWORD,
            Boolean::class.java
        )
        mDatabind.apply {
            sbClosePassword.setCheckedNoEvent(!closePassword)
            vFingerprintMask.visibility = if (sbClosePassword.isChecked) View.GONE else View.VISIBLE
            layoutFingerprint.alpha = if (sbClosePassword.isChecked) 1f else 0.3f
        }
        checkFingerprint()
//        setPretendPassword()
//        setPretendPasswordLogin()
        setCommonPassword()
    }

    private fun checkFingerprint() {
        //开启指纹
        val fingerprint = CacheSDK.get(
            IType.ICache.FINGERPRINT,
            Boolean::class.java
        )
        if (mManager == null || !mManager.isBiometricPromptEnable) {
            mDatabind.sbFingerprint.setCheckedNoEvent(false)
        } else {
            mDatabind.sbFingerprint.setCheckedNoEvent(fingerprint)
        }
    }


    /**
     * 设置通用密码
     */
    private fun setCommonPassword() {
        if (!BuildConfig.DEBUG) {
            return
        }
        mDatabind.apply {
            layoutCommonPassword.visibility = View.VISIBLE
            tvCommonPassword.text = EncodeNameUtils.decode(
                ConfigBean.getInstance().password
            )
        }
    }

    /**
     * 生物特征 - 指纹支付
     */
    private fun initBiometric() {
        val mManager =
            BiometricPromptManager.from(AppManager.getInstance().currentActivity(), true, true)
        if (mManager.isBiometricPromptEnable) {
            mManager.authenticate(false, object : OnBiometricIdentifyCallback {
                override fun onUsePassword() {}

                @RequiresApi(api = Build.VERSION_CODES.M)
                override fun onSucceeded(result: FingerprintManager.AuthenticationResult) {
                    val cipher = result.cryptoObject.cipher
                    ACacheUtils.setIV(activity, cipher)
                    setBiometric(true)
                }

                @RequiresApi(api = Build.VERSION_CODES.P)
                override fun onSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    val cipher = result.cryptoObject.cipher
                    ACacheUtils.setIV(activity, cipher)
                    setBiometric(true)
                }

                override fun onFailed() {
                    ToastUtils.showShort("指纹失败")
                    if (mDatabind.sbFingerprint != null) {
                        mDatabind.sbFingerprint.isChecked = false
                    }
                }

                override fun onError(code: Int, reason: String) {
                    ToastUtils.showShort(reason)
                    if (mDatabind.sbFingerprint != null) {
                        mDatabind.sbFingerprint.isChecked = false
                    }
                }

                override fun onCancel() {
                    //会调用onError ，无需自己处理
                }

                override fun onInvalid() {
                    ToastUtils.showLong("您的指纹有变更过，请从新开通")
                    if (mDatabind.sbFingerprint != null) {
                        mDatabind.sbFingerprint.isChecked = false
                    }
                }
            })
        } else {
            var content = ""
            if (!mManager.isKeyguardSecure) {
                content = "您的手机需要开启锁屏密码才能使用，注意是手机锁屏，不是我们app的锁屏，系统要求的。"
            } else if (!mManager.hasEnrolledFingerprints()) {
                content = "手机系统上至少录入一个指纹"
            } else if (!mManager.isHardwareDetected) {
                content = "请确保您的手机是否支持指纹功能"
            }
            CommonPop.Builder(context)
                .setCanceledOnTouchOutside(false)
                .setContent(content)
                .show()
            mDatabind.sbFingerprint.isChecked = false
        }
    }

    private fun setBiometric(isOpen: Boolean) {
        CacheSDK.put(IType.ICache.FINGERPRINT, isOpen)
        if (!fingerprintTips && isOpen) {
            fingerprintTips = true
            com.module.app.pop.CommonPop.Builder(context)
                .setCanceledOnTouchOutside(false)
                .setContent("如果您的爱人有您的指纹，这边建议您别开哦，避免您的爱人可以直接进入该APP，查看您的信息。")
                .setConfirmButton(R.string.i_konw)
                .show()
        }
    }
}